import { useEffect, useState } from 'react'
import type { MenuProps } from 'antd'
import { Menu } from 'antd'
import { Layout } from 'antd'
import { SettingInitialState } from '@/redux/slices/setting.slice'
import { useGetState } from '@/hooks/useRedux'
import { GlobalInitialState } from '@/redux/slices/global.slice'
import { useLocation, useNavigate } from 'react-router-dom'
import { RoutePathEnum } from '@/routes/localRouteList'

export type RouteMap = {
    [key: string]: RoutePathEnum
}
export default function SiderBar() {
    const setting = useGetState<SettingInitialState>('setting')
    const { authMenuTreeList } = useGetState<GlobalInitialState>('global')
    const navigate = useNavigate()
    const { pathname = '' } = useLocation()
    const [openKeys, setOpenKeys] = useState<string[]>([])
    const [selectedKeys, setSelectedKeys] = useState([pathname])
    const rootSubmenuKeys: string[] = authMenuTreeList.map((item) => item.key!)

    // 点击的菜单
    const onClick: MenuProps['onClick'] = (e) => {
        setSelectedKeys([e.key])
        navigate(e.key)
    }

    // 展开/关闭父级
    const onOpenChange: MenuProps['onOpenChange'] = (keys) => {
        if (setting.oneParentMenu) {
            const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1)
            if (rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
                setOpenKeys(keys)
            } else {
                setOpenKeys(latestOpenKey ? [latestOpenKey] : [])
            }
        } else {
            setOpenKeys(keys)
        }
    }

    // 路由映射关系
    // 目的: 当进入一些菜单栏没有对应的菜单选项的时候，可以映射为对应有菜单选项的路径
    const routeMap: RouteMap = {}

    useEffect(() => {
        // 获取路由
        const route = routeMap[pathname] || pathname
        // 根据浏览器地址展开相应的父级菜单
        const pathnameList = pathname.split('/').slice(1)
        let pathList = pathnameList.map((item, index) => {
            return `/${pathnameList.slice(0, index + 1).join('/')}`
        })
        setSelectedKeys([route])
        setOpenKeys(pathList)
    }, [pathname])

    return (
        <Layout.Sider width={setting.sidebarWidth} trigger={null} collapsible collapsed={setting.collapsed}>
            <div className="siderbar-content">
                <Logo />
                <div className='siderbar'>
                    <Menu
                        onClick={onClick}
                        onOpenChange={onOpenChange}
                        selectedKeys={selectedKeys}
                        openKeys={openKeys}
                        mode="inline"
                        items={authMenuTreeList}
                    ></Menu>
                </div>
            </div>
        </Layout.Sider>
    )
}

// LOGO
const Logo = () => {
    const { collapsed } = useGetState<SettingInitialState>('setting')

    return (
        <div className={`system-logo cursor-pointer ${collapsed && 'hide'}`}>
            <h2>中后台管理方案</h2>
        </div>
    )
}
